<?php

namespace App\Http\Services\MessageFetch\FetchWorker;

use Mockery\Exception;
use App\Common\Tools\RequestTools;
use App\Http\Services\MessageFetch\BaseMsgFetchHandle;

class DailyWoolWorkerLocal extends BaseMsgFetchHandle
{
    protected string $noticeType = 'timing_fleece';

    public String $txt = '';

    /**
     * 发送信息.
     *
     * @return void
     *
     * @throws \Throwable
     */
    protected function fetchUrlContent()
    {
        try {
            $this->fetchSuperXb();
        } catch (Exception $exception) {
            throw_if_str(true, '请求发送信息异常' . $exception->getMessage());
        }
    }

    private function fetchSuperXb()
    {
        $idPath    = storage_path('app/super_id.txt');
        $id        = intval(file_get_contents($idPath));
        $lastId    = 0;

        $this->url  = sprintf(config('wechat.wx_work.wool_super_url'), $id + 1);
        $content    = RequestTools::make()->withProxy()->request('get', $this->url);
        $res        = $ids        = [];
        $countLimit = 10;
        foreach ($content['data'] as $key => $datum) {
            if ($key >= $countLimit) {
                break;
            }

            preg_match('/ data-tooltip="(.*?)"/i', $datum, $matches);
            $title = $matches[1] ?? '';
            $title = str_replace(['[图]', '网页链接', '京红', '超红'], '', $title);
            if (empty($title)) {
                continue;
            }

            preg_match('/ data-id="(.*?)"/i', $datum, $match);
            $cid           = $match[1] ?? '';
            $cid && $ids[] = $cid;

            //黑名单的不提示 匹配到(>中文</b>)
            preg_match('/<span><b style="background:#[^"]+">([^<]+)<\/b>/i', $datum, $match);
            if ($match && !in_array($match[1], ['赚', '买', '奇', '咕', '仔', '丐', '女', '酱'])) {
                continue;
            }

            $res[] = ['id' => $cid, 'title' => trim($title)];
        }

        $lastId = current($ids) ?? $id;

        foreach ($res as $re) {
            //组装完整的提示信息
            $prefix    = $this->txt ? PHP_EOL . PHP_EOL : '';
            $this->txt .= $prefix . $re['title'] . '  https://cjx8.com/post/' . $re['id'];
        }

        //记录最后的id
        $lastId && file_put_contents($idPath, $lastId);
    }

    protected function afterLogic()
    {
        if (!empty($this->txt)) {
            RequestTools::make()->request('post', 'http://notice.ithook.cn/wechat/work_send_msg', ['text' => $this->txt]);
        }
    }
}
